package com.sxfq.loansupermarket.backsystem.modular.refunds.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.StringUtil;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.SearchCustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.CheckoutMethodInfo;
import com.sxfq.loansupermarket.backsystem.modular.marketing.entity.ReservationsAggregateInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.PaymentRecordInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.SearchPaymentRecordInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.SearchRechargeInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.service.IPaymentRecordService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 预约客户信息
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/paymentRecord")
public class PaymentRecordController extends BaseController {

    @Autowired
    IPaymentRecordService service;

    @Autowired
    ICustomerService customerService;

    @Autowired
    private SqlMapper sqlMapper;


    private String PREFIX = "/arrival/customer/";

    /**
     * 跳转到预约客户管理页面
     */
    @RequestMapping(value = "")
    public String recharge(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "/payment_record.html";
    }

    @RequestMapping(value = "/toUpdate/{ci}")
    public String toAddVisited(@PathVariable String ci, Model model) {
        String customerName = ci.split(",")[0];
        String id = ci.split(",")[1];
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String tableName = tableHead + "recharge_info";
        String sql = "select * from " + tableName + " where id='" + id + "' limit 0,1";
        PaymentRecordInfo paymentRecordInfo = sqlMapper.selectOne(sql, PaymentRecordInfo.class);
//        if (paymentRecordInfo == null) {
//            String sql1 = "select checkout_method as checkoutMethod,refund_money as actualAccountBalance  from " + tableName1 + " where id='" + id + "'";
//            paymentRecordInfo = sqlMapper.selectOne(sql1, PaymentRecordInfo.class);
//            paymentRecordInfo.setActualAccountBalance(paymentRecordInfo.getActualAccountBalance() - 2 * paymentRecordInfo.getActualAccountBalance());
//        }
        model.addAttribute("id", id);
        model.addAttribute("customerName", customerName);
        model.addAttribute("paymentRecordInfo", paymentRecordInfo);
        return PREFIX + "/update_checkout_method.html";
    }

    @RequestMapping(value = "/updateCheckoutMethod", method = RequestMethod.POST)
    @ResponseBody
    public int updateCheckoutMethod(String id, String checkoutMethod, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "recharge_info";
        String sql = "update " + tableName + " a set a.checkout_method='" + checkoutMethod + "' where a.id='" + id + "'";
        return sqlMapper.update(sql);
    }


    /**
     *
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object rechargeList(SearchPaymentRecordInfo info, HttpServletRequest request) {
        Page<PaymentRecordInfo> page = new PageFactory<PaymentRecordInfo>().defaultPage();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        try {
            info.setStartIndex(page.getSize() * (page.getCurrent() - 1));
            info.setLimitIndex(page.getSize());
            page.setCurrent(0);
            List<PaymentRecordInfo> list = service.selectPageListInfo(page, info);
            if (list.size() == 0) {
                info.setStartIndex(0);
                list = service.selectPageListInfo(page, info);
            }
            page.setTotal(service.getQueryPagesCount(page, info));
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }

    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @ResponseBody
    public List<Map<String, Object>> getList() {
        List<Map<String, Object>> list = service.list();
        return list;
    }

    @RequestMapping("/sumBorrowAmount")
    @ResponseBody
    public HashMap sumBorrowAmount(@RequestParam(required = false) String customerName,
                                   @RequestParam(required = false) String customerPhone,
                                   @RequestParam(required = false) String checkoutMethod,
                                   @RequestParam(required = false) String reach,
                                   @RequestParam(required = false) String fieldTc,
                                   @RequestParam(required = false) String doctor,
                                   @RequestParam(required = false) String startTime,
                                   @RequestParam(required = false) String xcustomerStatus,
                                   @RequestParam(required = false) String endTime) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName1 = tableHead + "recharge_info";
        String sql = " select sum(t1.actualAccountBalance) as borrowAmount_sum from ( select t1.id as id,t1.customer_id as customerId ,t1.record_people as recordPeople,\n" +
                "        t1.reservations_id as reservationsId,t1.operation_time as operationTime,t1.checkout_method as checkoutMethod,t1.recharge_time as rechargeTime,\n" +
                "        t1.remarks as remarks , t2.customer_name as customerName ,t2.customer_phone as customerPhone,t2.doctor as doctor,\n" +
                "        t1.record_time as recordTime,t1.actual_account_balance as actualAccountBalance, t2.customer_status as customerStatus,\n" +
                "        t2.customer_sex as customerSex ,t2.customer_age as customerAge,t2.field_tc as fieldTc\n" +
                "        from " + tableName1 + " t1 left join " + this.getTableName() + " t2 on t1.customer_id=t2.id\n" +
                "        where 1=1";
        if (StringUtil.isNotEmpty(customerName)) {
            sql += " and t2.customer_name = '" + customerName + "'";
        }
        if (StringUtil.isNotEmpty(customerPhone)) {
            sql += " and t2.customer_phone = '" + customerPhone + "'";
        }
        if (StringUtils.isNoneEmpty(reach)) {  //结账时间
            sql += "  and (t2.customer_name like CONCAT('%','" + reach + "','%') or t2.customer_phone like CONCAT('%','" + reach + "','%') or\n" +
                    " t2.wechat_number like CONCAT('%','" + reach + "','%') or t2.medical_record_number like CONCAT('%','" + reach + "','%')) ";
        }
        if (StringUtil.isNotEmpty(fieldTc)) {
            sql += " and t2.field_tc = '" + fieldTc + "'";
        }
        if (StringUtil.isNotEmpty(xcustomerStatus)) {
            sql += " and t2.xcustomer_status = '" + xcustomerStatus + "'";
        }
        if (StringUtil.isNotEmpty(doctor)) {
            sql += " and t2.doctor = '" + doctor + "'";
        }
        if (StringUtil.isNotEmpty(startTime)) {
            sql += " and t1.recharge_time >= '" + startTime + "'";
        }
        if (StringUtil.isNotEmpty(endTime)) {
            sql += " and t1.recharge_time <= '" + endTime + "'";
        }
        sql += "  ) t1   where 1=1 ";
        if (StringUtil.isNotEmpty(checkoutMethod)) {
            sql += " and t1.checkoutMethod = '" + checkoutMethod + "'";
        }
        sql += " order by t1.recordTime DESC;";
        Map<String, Object> result = sqlMapper.selectOne(sql.toString());
        HashMap map = new HashMap();
        if (result != null) {
            map.put("borrowAmount_sum", result.get("borrowAmount_sum"));
        } else {
            map.put("borrowAmount_sum", "0");
        }
        return map;
    }

    @RequestMapping(value = "/paymentExport")
    public void paymentExport(@RequestParam(required = false) String startTime, @RequestParam(required = false) String endTime,
                              HttpServletResponse response) {
        try {
            SearchPaymentRecordInfo searchInfo = new SearchPaymentRecordInfo();
            searchInfo.setStartArrivalTime(startTime);
            searchInfo.setEndArrivalTime(endTime);
            List<PaymentRecordInfo> list = service.paymentRecordExport(searchInfo);
            // 解析成excel文件
            // 第一步，创建一个webbook，对应一个Excel文件
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在wb中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet("前端导出");
            for (int i = 0; i < 19; i++) {
                sheet.setColumnWidth(i, 24 * 256);
            }
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);// 创建一个居中格式
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("年");
            cell.setCellStyle(style);
            cell = row.createCell(1);
            cell.setCellValue("月");
            cell.setCellStyle(style);
            cell = row.createCell(2);
            cell.setCellValue("日");
            cell.setCellStyle(style);
            cell = row.createCell(3);
            cell.setCellValue("姓名");
            cell.setCellStyle(style);
            cell = row.createCell(4);
            cell.setCellValue("病例号");
            cell.setCellStyle(style);
            cell = row.createCell(5);
            cell.setCellValue("单据号");
            cell.setCellStyle(style);
            cell = row.createCell(6);
            cell.setCellValue("TC");
            cell.setCellStyle(style);
            cell = row.createCell(7);
            cell.setCellValue("助理TC");
            cell.setCellStyle(style);
            cell = row.createCell(8);
            cell.setCellValue("主治医生");
            cell.setCellStyle(style);
            cell = row.createCell(9);
            cell.setCellValue("医助/护士");
            cell.setCellStyle(style);
            cell = row.createCell(10);
            cell.setCellValue("转诊人");
            cell.setCellStyle(style);
            cell = row.createCell(11);
            cell.setCellValue("到店途径");
            cell.setCellStyle(style);
            cell = row.createCell(12);
            cell.setCellValue("牙位");
            cell.setCellStyle(style);
            cell = row.createCell(13);
            cell.setCellValue("类别");
            cell.setCellStyle(style);
            cell = row.createCell(14);
            cell.setCellValue("项目");
            cell.setCellStyle(style);
            cell = row.createCell(15);
            cell.setCellValue("折扣/活动价");
            cell.setCellStyle(style);
            cell = row.createCell(16);
            cell.setCellValue("总费用");
            cell.setCellStyle(style);
            cell = row.createCell(17);
            cell.setCellValue("现金");
            cell.setCellStyle(style);
            cell = row.createCell(18);
            cell.setCellValue("扫码收款");
            cell.setCellStyle(style);
            cell = row.createCell(19);
            cell.setCellValue("刷卡");
            cell.setCellStyle(style);
            cell = row.createCell(20);
            cell.setCellValue("医保");
            cell.setCellStyle(style);
            cell = row.createCell(21);
            cell.setCellValue("分期贷款");
            cell.setCellStyle(style);
            cell = row.createCell(22);
            cell.setCellValue("美团");
            cell.setCellStyle(style);
            cell = row.createCell(23);
            cell.setCellValue("华荣");
            cell.setCellStyle(style);
            cell = row.createCell(24);
            cell.setCellValue("糯米");
            cell.setCellStyle(style);
            cell = row.createCell(25);
            cell.setCellValue("积分抵扣");
            cell.setCellStyle(style);
            cell = row.createCell(26);
            cell.setCellValue("代金劵");
            cell.setCellStyle(style);
            cell = row.createCell(27);
            cell.setCellValue("VIP消费");
            cell.setCellStyle(style);
            cell = row.createCell(28);
            cell.setCellValue("欠费");
            cell.setCellStyle(style);
            cell = row.createCell(29);
            cell.setCellValue("分期收费");
            cell.setCellStyle(style);
            cell = row.createCell(30);
            cell.setCellValue("正畸编号");
            cell.setCellStyle(style);
            cell = row.createCell(31);
            cell.setCellValue("初诊地");
            cell.setCellStyle(style);
            cell = row.createCell(32);
            cell.setCellValue("电话查询");
            cell.setCellStyle(style);
            cell = row.createCell(33);
            cell.setCellValue("新诊复诊");
            cell.setCellStyle(style);
            cell = row.createCell(34);
            cell.setCellValue("备注");
            cell.setCellStyle(style);

            // 填充数据
            for (int i = 0; i < list.size(); i++) {
                PaymentRecordInfo map = list.get(i);
                row = sheet.createRow(i + 1);
                int customerAge = 0;
                if (map.getCustomerAge() != null) {
                    customerAge = map.getCustomerAge();
                }
                String sex = map.getSex();
                String customerName = map.getCustomerName();
                String medicalRecordNumber = map.getMedicalRecordNumber();
                String appointmentPayService = map.getAppointmentPayService();
                String fieldTc = map.getFieldTc();
                String doctor = map.getDoctor();
                String documentNumber = map.getDoctor();
                sex = map.getSex();
                String medicalAssistance = map.getMedicalAssistance();
                String id = map.getId();
                String referraler = map.getReferraler();
                String oneChannel = map.getOneChannel();
                String toothPosition = map.getOneChannel();
                String department = map.getDepartment();
                String payServiceName = map.getDepartment();
                String discount = map.getDiscount();
                Double xj = map.getXj();
                Double sm = map.getSm();
                Double sk = map.getSk();
                Double yb = map.getYb();
                Double fqdk = map.getFqdk();
                Double mt = map.getMt();
                Double hr = map.getHr();
                Double nm = map.getNm();
                Double jfdk = map.getJfdk();
                Double djq = map.getDjq();
                Double vip = map.getVip();
                Double qf = map.getQf();
                Double fqsf = map.getFqsf();
                String orthodonticNumber = map.getOrthodonticNumber();
                String firstDiagnosis = map.getFirstDiagnosis();
                String customerPhone = map.getCustomerPhone();
                String newReview = map.getNewReview();
                String remarks = map.getRemarks();
                // 第四步，创建单元格，并设置值
                for (int j = 0; j <= 14; j++) {
                    row.createCell(j).setCellStyle(style);
                }
                row.getCell(0).setCellValue(startTime.substring(0, 4));
                row.getCell(1).setCellValue(startTime.substring(5, 7));
                row.getCell(2).setCellValue(startTime.substring(8, 10));
                row.getCell(3).setCellValue(customerName);
                row.getCell(4).setCellValue(medicalRecordNumber);
                row.getCell(5).setCellValue(customerAge);
                row.getCell(6).setCellValue(fieldTc);
                row.getCell(7).setCellValue("助理TC");
                row.getCell(8).setCellValue(doctor);
                row.getCell(9).setCellValue(medicalAssistance);
                row.getCell(10).setCellValue(referraler);
                row.getCell(11).setCellValue(oneChannel);
                row.getCell(12).setCellValue(toothPosition);
                row.getCell(13).setCellValue(department);
                row.getCell(14).setCellValue(payServiceName);
                row.getCell(15).setCellValue(discount);
                row.getCell(16).setCellValue(discount);
                row.getCell(17).setCellValue(xj);
                row.getCell(18).setCellValue(sm);
                row.getCell(19).setCellValue(sk);
                row.getCell(20).setCellValue(yb);
                row.getCell(21).setCellValue(fqdk);
                row.getCell(22).setCellValue(mt);
                row.getCell(23).setCellValue(hr);
                row.getCell(24).setCellValue(nm);
                row.getCell(25).setCellValue(jfdk);
                row.getCell(26).setCellValue(djq);
                row.getCell(27).setCellValue(vip);
                row.getCell(28).setCellValue(qf);
                row.getCell(29).setCellValue(fqsf);
                row.getCell(30).setCellValue(orthodonticNumber);
                row.getCell(31).setCellValue(firstDiagnosis);
                row.getCell(32).setCellValue(customerPhone);
                row.getCell(33).setCellValue(newReview);
                row.getCell(34).setCellValue(remarks);
            }
            String date = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
            String filename = "data" + date + ".xls";
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + URLEncoder.encode(filename, "UTF-8") + "\"");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }
}
